package com.example.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.common.utils.HttpUtils;
import com.example.gulimall.member.dao.MemberLevelDao;
import com.example.gulimall.member.exception.PhoneExistException;
import com.example.gulimall.member.exception.UsernameExistException;
import com.example.gulimall.member.vo.MemberLoginVo;
import com.example.gulimall.member.vo.MemberRegistVo;
import com.example.gulimall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.utils.PageUtils;
import com.example.common.utils.Query;

import com.example.gulimall.member.dao.MemberDao;
import com.example.gulimall.member.entity.MemberEntity;
import com.example.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao levelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {
        MemberEntity memberEntity = new MemberEntity();

        memberEntity.setLevelId(levelDao.getDefaultLevel());

        //检查用户名和手机号是否存在
        checkPhoneUnique(vo.getPhone());
        memberEntity.setMobile(vo.getPhone());

        memberEntity.setUsername(vo.getUsername());

        // 利用加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        memberEntity.setPassword(bCryptPasswordEncoder.encode(vo.getPassword()));
        baseMapper.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) {
        Integer mobile = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if(mobile > 0)
        throw new PhoneExistException();
    }

    @Override
    public void checkUsernameUnique(String username) {
        Integer user = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if(user > 0)
        throw new UsernameExistException();
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();

        // 1.去数据库查询
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>()
                .eq("username", loginacct).or().eq("mobile",loginacct));
        if (memberEntity == null){
            //登陆失败
            return null;
        } else {
          String pwDb = memberEntity.getPassword();
          BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
          if(encoder.matches(password,pwDb))
              return memberEntity;
          else
              return null;
        }


    }

    @Override
    public MemberEntity login(SocialUser vo) {

        String uid = vo.getUid();
        MemberEntity memberEntity = new MemberEntity();
        MemberEntity entity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if(entity != null){
            // 已经注册了
            memberEntity.setId(entity.getId());
            memberEntity.setAccessToken(vo.getAccess_token());
            memberEntity.setExpiresIn(vo.getExpires_in());
            baseMapper.updateById(memberEntity);

            entity.setAccessToken(vo.getAccess_token());
            entity.setExpiresIn(vo.getExpires_in());
            return entity;
        }else{

            Map<String, String> map = new HashMap<>();
            map.put("access_token", vo.getAccess_token());
            map.put("uid", vo.getUid());
            // 通过微博去查各种信息
            try{
                System.out.println(vo.getAccess_token() +" ====== "+ vo.getUid());
                // 3. 查询当前社交用户账号信息(昵称、性别、头像等)
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<>(), map);
                System.out.println(response.getStatusLine().getStatusCode()+"此时的code是");
                if(response.getStatusLine().getStatusCode() == 200) {
                    // 查询成功
                    String json = EntityUtils.toString(response.getEntity());
                    System.out.println(json);
                    // 这个JSON对象什么样的数据都可以直接获取
                    JSONObject jsonObject = JSON.parseObject(json);
                    memberEntity.setNickname(jsonObject.getString("name"));
                    memberEntity.setUsername(jsonObject.getString("name"));
                    memberEntity.setGender("m".equals(jsonObject.getString("gender"))?1:0);
                    memberEntity.setCity(jsonObject.getString("location"));
                    memberEntity.setJob("自媒体");
                    memberEntity.setEmail(jsonObject.getString("email"));
                }
            }catch (Exception e){
                log.warn("尝试修复错误");
            }
            memberEntity.setStatus(0);
            memberEntity.setCreateTime(new Date());
            memberEntity.setBirth(new Date());
            memberEntity.setLevelId(1L);
            memberEntity.setSocialUid(vo.getUid());
            memberEntity.setAccessToken(vo.getAccess_token());
            memberEntity.setExpiresIn(vo.getExpires_in());
            // 注册 -- 登录成功
            baseMapper.insert(memberEntity);
            memberEntity.setPassword(null);
            return memberEntity;
        }
    }

}